//
//  TGDistrictMenu.m
//  GroupBuy
//
//  Created by wwj on 15/11/4.
//  Copyright © 2015年 wwj. All rights reserved.
//

#import "TGDistrictMenu.h"
#import "TGDistrictMenuItem.h"
#import "TGDistrictModel.h"

@interface TGDistrictMenu ()
@property (strong, nonatomic) NSMutableArray *btnArray;
@end

@implementation TGDistrictMenu
- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        _btnArray = [NSMutableArray array];
        [self cityChangeNotification];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cityChangeNotification) name:kCityChange object:nil];
    }
    return self;
}

- (void)cityChangeNotification{
    TGCityModel *city = [TGDataTool shareDataTool].currentCity;
    
    NSMutableArray *array = [NSMutableArray array];
    TGDistrictModel *all = [[TGDistrictModel alloc] init];
    all.name = kAllDistrictStr;
    [array addObject:all];
    [array addObjectsFromArray:city.districts];
    
    
    for (int index = 0; index < array.count; index++) {
        TGDistrictMenuItem *btn;
        if (index < _btnArray.count) {
            btn = _btnArray[index];
        }else{
            btn = [[TGDistrictMenuItem alloc] init];
            [_btnArray addObject:btn];
        }
        btn.hidden = NO;
        btn.model = array[index];
        btn.frame = CGRectMake(kBottomMenuItemW * index, 0, 0, 0);
        [self.scrollerView addSubview:btn];
        [btn addTarget:self action:@selector(onClickItemBtn:) forControlEvents:UIControlEventTouchUpInside];
        
        // 默认选中第0个item
        if (index == 0) {
            btn.selected = YES;
            self.itemBtn = btn;
        } else {
            btn.selected = NO;
        }

        
    }
    self.scrollerView.contentSize = CGSizeMake(kBottomMenuItemW * array.count, 0);
    
    for (int index = array.count; index < _btnArray.count; index++) {
        TGDistrictMenuItem *btn = _btnArray[index];
        btn.hidden = YES;
    }
    
    [self.subtitlesView hidden];
}

-(void)onSelectItemBtn:(TGBottomMenuItem *)itemBtn{
    [TGDataTool shareDataTool].currentDistrict = [itemBtn titleForState:UIControlStateNormal];
}

-(void)setSubTitle{
    self.subtitlesView.setTitleBlock = ^(NSString *title){
        [TGDataTool shareDataTool].currentDistrict = title;
    };
    
    self.subtitlesView.getTitleBlock = ^(){
        return [TGDataTool shareDataTool].currentDistrict;
    };
}
@end
